package com.example.auth.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.i18n.api.AjaxJson;
import com.example.common.i18n.util.MessageUtils;
import com.example.common.i18n.util.ResponseUtil;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomFilter implements Filter {

    public static final String OAUTH_TOKEN_URL = "/oauth/token,/mobile/token";

    public static final String ACCESS_TOKEN = "access_token";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        CustomResponseWrapper wrapperResponse = new CustomResponseWrapper((HttpServletResponse) servletResponse);// 转换成代理类
        // 这里只拦截返回，直接让请求过去，如果在请求前有处理，可以在这里处理

        filterChain.doFilter(servletRequest, wrapperResponse);
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String url = httpServletRequest.getRequestURI();
        byte[] content = wrapperResponse.getContent();// 获取返回值
        String str = new String(content, "UTF-8");

        // 是否登录请求
        if (StrUtil.containsAnyIgnoreCase(OAUTH_TOKEN_URL, url)) {
            if (content.length > 0) {
                JSONObject obj = JSON.parseObject(str);
                AjaxJson ajaxJson = new AjaxJson();
                if (obj.containsKey(ACCESS_TOKEN)) {
                    String accessToken = obj.getString(ACCESS_TOKEN);
                    ajaxJson = MessageUtils.success(0,"PUBLIC-SUCCESS",obj);
                }else {
                    String errorMsg = obj.getString("error_description");
                    ajaxJson =  MessageUtils.error(errorMsg);
                }
                ResponseUtil.printJson((HttpServletResponse) servletResponse, ajaxJson);
            }
        } else {
            ResponseUtil.printJson((HttpServletResponse) servletResponse, str);
        }
    }

}
